<template>
    <div class="drawOuter fadeInRight">
        <div class="drawinner">
            <div class="title">
                <header>
                    <span>基础标绘</span>
                    <i class="close el-icon-close" alt @click="closePenal" />
                </header>
                <el-row>
                    <img class="line" src="./theme/img/sit/headerline.png" alt />
                </el-row>
            </div>
            <div class="drawtree">
                <el-tree
                    ref="tree"
                    :props="props"
                    :data="treeData"
                    show-checkbox
                    node-key="id"
                    @check-change="handleCheckChange"
                    :default-expand-all="true"
                >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span
                            @contextmenu="showMenu($event, node)"
                            class="title"
                            @dblclick="lookTarget(node)"
                        >
                            <span
                                class="icon"
                                v-if="data.type"
                                :class="{
                                    point: data.type == 'Marker',
                                    word: data.type == 'Text',
                                    line: data.type == 'GroundPolyline',
                                    circle: data.type == 'GroundCircle',
                                    rectangle: data.type == 'GroundRectangle',
                                    oval: data.type == 'GroundEllipse',
                                    surface: data.type == 'GroundPolygon',
                                }"
                            ></span>
                            {{ node.label }}
                        </span>
                        <!-- <el-input @dblclick="showInput"></el-input> -->
                    </span>
                </el-tree>
                <input
                    type="text"
                    v-show="changeLable"
                    @keyup.enter="changNode($event)"
                    ref="input"
                />
                <contextmenu
                    :menu="menu"
                    :pos="pos"
                    v-if="menushow"
                    @rename="rename"
                    @delLayers="delLayers"
                    @empty="empty"
                    @setActLay="setActLay"
                    @newLayer="newLayer"
                    @editLayer="editLayer"
                ></contextmenu>
            </div>
            <el-row>
                <el-button @click="startSavePlan('openPlanList')" class="file">打开</el-button>
                <el-button @click="startSavePlan('newPlan')" class="file">新建</el-button>
                <el-button @click="endSavePlan" class="file">保存</el-button>
            </el-row>
            <img src="./theme/img/draw/splitline.png" alt class="splitline" />
            <div class="drawtools">
                <markPage
                    ref="markPage"
                    @addLeafNode="addLeafNode"
                    @getLayerId="getLayerId"
                ></markPage>
            </div>
            <Dialog v-show="savePanel">
                <div class="saved">
                    <div class="inner">
                        <p>是否保存当前方案？</p>
                        <div class="buttenrow">
                            <el-button class="file" @click="endSavePlan">保存</el-button>
                            <el-button
                                class="file con"
                                @click="
                                    () => {
                                        this[saveThen]();
                                        this.savePanel = false;
                                    }
                                "
                            >
                                不保存，继续
                            </el-button>
                            <el-button class="file" @click="cancel">取消</el-button>
                        </div>
                    </div>
                </div>
            </Dialog>
            <Dialog v-show="saveNameShow">
                <div class="saved">
                    <div class="inner">
                        <el-row>
                            <label>
                                方案名称
                                <input
                                    type="text"
                                    v-model="saveName"
                                    @keydown.enter="startSaveName"
                                />
                            </label>
                        </el-row>
                        <div class="buttenrow">
                            <el-button class="file" @click="startSaveName">确定</el-button>
                            <el-button class="file" @click="cancel">取消</el-button>
                        </div>
                    </div>
                </div>
            </Dialog>
            <Dialog v-show="radioShow" class="choose">
                <div class="title">选择方案</div>
                <el-select v-model="radio" placeholder="请选择">
                    <el-option
                        v-for="(item, i) in planList"
                        :key="i"
                        :label="item.name"
                        :value="i"
                    ></el-option>
                </el-select>
                <el-button @click="makeSure(planList[radio])">确定</el-button>
                <el-button @click="closeRadio">取消</el-button>
            </Dialog>
        </div>
    </div>
</template>

<script>
/* global Cesium viewer */
// Marker 点
// Text   文字
// GroundPolyline  线
// GroundCircle   圆
// GroundRectangle 矩形
// GroundEllipse   椭圆
// GroundPolygon   面
import contextmenu from './contextmenu';
import markPage from './markPage';
import Dialog from './Dialog';
import { getAllPlan, getOnePlan, extPlan, updatePlan } from 'S/themeTic';

export default {
    data() {
        return {
            props: {
                label: 'label',
                children: 'children',
            },
            treeData: [
                {
                    id: Cesium.createGuid(),
                    label: '默认方案',
                    children: [
                        {
                            id: Cesium.createGuid(),
                            label: '默认图层',
                            children: [],
                        },
                    ],
                },
            ],
            dataId: null,
            changeLable: false,
            menushow: false,
            menu: null,
            pos: {},
            curNode: null,
            curHTML: null,
            planList: null,
            radioShow: false,
            savePanel: false,
            saveThen: null,
            saveNameShow: false,
            saveName: null,
            radio: 0,
        };
    },
    methods: {
        closePenal() {
            this.$parent.closeBh();
        },
        handleCheckChange(data, flag) {
            if (data.isLeaf) {
                Cesium.C_layerGroupHandle.showGeometry(data.id, flag);
            }
        },
        lookTarget(node) {
            if (node.isLeaf) {
                Cesium.C_layerGroupHandle.lookGeometry(node.data.id);
            }
        },
        showMenu(e, node) {
            let renameObj = {};
            let delLayersObj = {};
            let emptyObj = {};
            let setActLayObj = {};
            let newLayerObj = {};
            let editLayerObj = {};
            switch (e.button) {
                case 2:
                    this.pos.left = e.x + document.body.scrollLeft + 'px';
                    this.pos.top = e.y + document.body.scrollTop + 'px';
                    this.curNode = node;
                    this.curHTML = e.target;
                    renameObj = {
                        name: '重命名',
                        fun: 'rename',
                    };
                    delLayersObj = {
                        name: '删除',
                        fun: 'delLayers',
                    };
                    emptyObj = {
                        name: '清空',
                        fun: 'empty',
                    };
                    setActLayObj = {
                        name: '设为活动图层',
                        fun: 'setActLay',
                    };
                    newLayerObj = {
                        name: '新建图层',
                        fun: 'newLayer',
                    };
                    editLayerObj = {
                        name: '编辑',
                        fun: 'editLayer',
                    };
                    switch (node.level) {
                        case 1:
                            this.menu = [emptyObj, newLayerObj, renameObj];
                            break;
                        case 2:
                            this.menu = [emptyObj, renameObj, delLayersObj, setActLayObj];
                            break;
                        case 3:
                            this.menu = [renameObj, delLayersObj, editLayerObj];
                            break;
                    }
                    this.menushow = true;
                    document.addEventListener('click', this.closeMune, true);
                    break;
            }
        },
        changNode(e) {
            this.curNode.data.label = this.$refs.input.value;
            this.$refs.input.value = '';
            this.changeLable = false;
            this.curHTML.removeChild(this.$refs.input);
            document.removeEventListener('click', this.closeRename, false);
        },
        rename() {
            this.menushow = false;
            document.removeEventListener('click', this.closeMune, true);
            this.curHTML.appendChild(this.$refs.input);
            this.changeLable = true;
            this.$refs.input.autofocus = true;
            document.addEventListener('click', this.closeRename, true);
        },
        closeRename(e) {
            if (e.target !== this.$refs.input && e.target.className !== 'menuCon') {
                this.changeLable = false;
                this.curHTML.removeChild(this.$refs.input);
                document.removeEventListener('click', this.closeRename, false);
            }
        },
        delLayers() {
            this.menushow = false;
            document.removeEventListener('click', this.closeMune, true);
            const parent = this.curNode.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d.id === this.curNode.data.id);
            children.splice(index, 1);
            this.curNode.level === 2 &&
                Cesium.C_layerGroupHandle.deleteLayer(parent.data.id, this.curNode.data.id);
            this.curNode.level === 3 &&
                Cesium.C_layerGroupHandle.removeGeometry(
                    this.curNode.data.id,
                    parent.parent.data.id,
                    parent.data.id
                );
            this.curNode.level === 2 &&
                this.curNode.data.id === this.activeLayer &&
                (this.activeLayer = undefined);
        },
        empty() {
            this.menushow = false;
            document.removeEventListener('click', this.closeMune, true);
            this.curNode.data.children = [];
            new Cesium.C_DrawHelper(viewer.scene).stopDrawing();
            if (this.curNode.level === 1) {
                Cesium.C_layerGroupHandle.clearLayerGroup(this.curNode.data.id);
                this.activeLayer = undefined;
            }
            this.curNode.level === 2 &&
                Cesium.C_layerGroupHandle.clearLayer(
                    this.curNode.parent.data.id,
                    this.curNode.data.id
                );
        },
        setActLay() {
            this.activeLayer = this.curNode.data.id;
            this.activeLayerParent = this.curNode.parent.data.id;
            Cesium.C_layerGroupHandle.setActiveLayer(this.activeLayerParent, this.activeLayer);
            this.menushow = false;
            document.removeEventListener('click', this.closeMune, true);
        },
        newLayer() {
            this.menushow = false;
            document.removeEventListener('click', this.closeMune, true);
            const newChild = { id: Cesium.createGuid(), label: '默认图层', children: [] };
            this.curNode.data.children.push(newChild);
            Cesium.C_layerGroupHandle.addLayer(this.curNode.data.id, newChild.id, newChild.label);
        },
        editLayer() {
            Cesium.C_layerGroupHandle.getGeometry(this.curNode.data.id).setEditMode(true);
            this.menushow = false;
        },
        closeMune(e) {
            if (e.target.className !== 'menuCon') {
                this.menushow = false;
                document.removeEventListener('click', this.closeMune, true);
            }
        },

        async openPlanList() {
            getAllPlan().then(res => {
                this.planList = res.data;
                this.radioShow = true;
            });
        },
        async makeSure(planCon) {
            getOnePlan(planCon.id).then(res => {
                let _self = this;
                let arr = res.data.content.split('|');
                this.treeData = JSON.parse(arr[0]);
                this.initLayers();
                setTimeout(function() {
                    _self.$refs.tree.setChecked(_self.treeData[0].id, true, true);
                }, 0);
                let programme = JSON.parse(arr[1]);
                Cesium.C_layerGroupHandle.openProgramme(programme, viewer.scene, {
                    startEditCallback: this.$refs.markPage.startEditCallback,
                    endEditCallback: this.$refs.markPage.endEditCallback,
                });
                // _self.$parent.$refs.imageManage.leftCompareRight = true
                if (window.rightViewer) {
                    setTimeout(function() {
                        let geometryArr = Cesium.C_layerGroupHandle.getAllGeometry();
                        for (let i in geometryArr) {
                            if (i === 'size') {
                                continue;
                            }
                            if (geometryArr[i].properties.isRight) {
                                let options = _self.getOptions(geometryArr[i]);
                                let node = _self.$refs.tree.getNode(i);
                                Cesium.C_layerGroupHandle.removeGeometry(
                                    node.data.id,
                                    node.parent.parent.data.id,
                                    node.parent.data.id
                                );
                                let geometry = _self.createPrimitive(options);
                                geometryArr[i] = geometry;
                                geometry._createPrimitive = true;
                                let callbacks = _self.$refs.markPage.createCallbacks();
                                geometry.startEditCallback = callbacks.startEditCallback;
                                geometry.endEditCallback = callbacks.endEditCallback;
                                // geometry._primitives = rightViewer.scene.primitives;
                                // rightViewer.scene.primitives.add(geometry);
                            }
                        }
                    }, 0);
                } else {
                    setTimeout(function() {
                        let geometryArr = Cesium.C_layerGroupHandle.getAllGeometry();
                        for (let i in geometryArr) {
                            if (i === 'size') {
                                continue;
                            }
                            if (geometryArr[i].properties.isRight) {
                                _self.curNode = _self.$refs.tree.getNode(i);
                                _self.delLayers();
                            }
                        }
                    }, 0);
                }

                this.dataId = res.data.id;
            });
            this.cancel();
        },
        getOptions(primitive) {
            let result = {};
            switch (primitive.getType()) {
                case 'Marker':
                    result.id = primitive.id;
                    result.type = 'Marker';
                    result.position = Cesium.Cartesian3.pack(primitive._billboards[0].position, []);
                    result.image = primitive._billboards[0].image;
                    result.color = primitive._billboards[0].color;
                    result.scale = primitive._billboards[0].scale;
                    result.properties = primitive._billboards[0].properties;
                    break;
                case 'Text':
                    result.id = primitive.id;
                    result.type = 'Text';
                    result.position = Cesium.Cartesian3.pack(primitive._labels[0].position, []);
                    result.text = primitive._labels[0].text;
                    result.font = primitive._labels[0].font;
                    result.fillColor = primitive._labels[0].fillColor;
                    result.outlineColor = primitive._labels[0].outlineColor;
                    result.outlineWidth = primitive._labels[0].outlineWidth;
                    result.properties = primitive._labels[0].properties;
                    break;
                case 'GroundPolyline':
                    result.id = primitive.id;
                    result.type = 'GroundPolyline';
                    result.positions = Cesium.Cartesian3.packArray(primitive.positions, []);
                    result.width = primitive.width;
                    result.lineType = primitive.lineType;
                    result.color = primitive.color;
                    result.outlineWidth = primitive.outlineWidth;
                    result.outlineColor = primitive.outlineColor;
                    result.glowPower = primitive.glowPower;
                    result.taperPower = primitive.taperPower;
                    result.dashedScale = primitive.dashedScale;
                    result.dashedLength = primitive.dashedLength;
                    result.properties = primitive.properties;
                    break;
                case 'GroundPolygon':
                    result.id = primitive.id;
                    result.type = 'GroundPolygon';
                    result.positions = Cesium.Cartesian3.packArray(primitive.positions, []);
                    result.color = primitive.color;
                    result.outlineColor = primitive.outlineColor;
                    result.properties = primitive.properties;
                    break;
                case 'GroundEllipse':
                    result.id = primitive.id;
                    result.type = 'GroundEllipse';
                    result.center = Cesium.Cartesian3.pack(primitive.getCenter(), []);
                    result.rotation = primitive.getRotation();
                    result.color = primitive.color;
                    result.semiMajorAxis = primitive.semiMajorAxis;
                    result.semiMinorAxis = primitive.semiMinorAxis;
                    result.properties = primitive.properties;
                    break;
                case 'GroundCircle':
                    result.id = primitive.id;
                    result.type = 'GroundCircle';
                    result.color = primitive.color;
                    result.center = Cesium.Cartesian3.pack(primitive.getCenter(), []);
                    result.radius = primitive.getRadius();
                    result.properties = primitive.properties;
                    break;
                case 'GroundRectangle':
                    result.id = primitive.id;
                    result.type = 'GroundRectangle';
                    result.color = primitive.color;
                    result.extent = primitive.getExtent();
                    result.properties = primitive.properties;
                    break;
            }
            return result;
        },
        createPrimitive(options) {
            let primitive = null;
            // options.scene = rightViewer.scene;
            switch (options.type) {
                case 'Marker':
                    options.position = Cesium.Cartesian3.unpack(options.position);
                    options.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND;
                    primitive = new Cesium.Marker(options);
                    break;
                case 'Text':
                    options.position = Cesium.Cartesian3.unpack(options.position);
                    options.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND;
                    primitive = new Cesium.TextAnnotation(options);
                    break;
                case 'GroundPolyline':
                    options.positions = Cesium.Cartesian3.unpackArray(options.positions);
                    primitive = new Cesium.GroundPolyline(options);
                    break;
                case 'GroundPolygon':
                    options.positions = Cesium.Cartesian3.unpackArray(options.positions);
                    primitive = new Cesium.GroundPolygon(options);
                    break;
                case 'GroundEllipse':
                    options.center = Cesium.Cartesian3.unpack(options.center);
                    primitive = new Cesium.GroundEllipse(options);
                    break;
                case 'GroundCircle':
                    options.center = Cesium.Cartesian3.unpack(options.center);
                    primitive = new Cesium.GroundCircle(options);
                    break;
                case 'GroundRectangle':
                    primitive = new Cesium.GroundRectangle(options);
                    break;
            }
            return primitive;
        },
        newPlan() {
            this.treeData = [
                {
                    id: Cesium.createGuid(),
                    label: '默认方案',
                    children: [
                        {
                            id: Cesium.createGuid(),
                            label: '默认图层',
                            children: [],
                        },
                    ],
                },
            ];
            this.$refs.tree.setChecked(1, true, true);
            this.initLayers();
            this.cancel();
        },
        initLayers() {
            Cesium.C_layerGroupHandle.deleteLayerGroup(this.activeLayerParent);
            this.activeLayerParent = this.treeData[0].id;
            this.activeLayer = this.treeData[0].children[0].id;
            Cesium.C_layerGroupHandle.addLayerGroup(this.activeLayerParent, '默认方案');
            Cesium.C_layerGroupHandle.addLayer(
                this.activeLayerParent,
                this.activeLayer,
                '默认图层'
            );
            Cesium.C_layerGroupHandle.setActiveLayer(this.activeLayerParent, this.activeLayer);
        },
        startSavePlan(callback) {
            this.savePanel = true;
            if (callback) {
                this.saveThen = callback;
            }
        },
        async endSavePlan() {
            this.savePanel = false;
            this.saveName = this.treeData[0].label;
            this.saveNameShow = true;
        },
        async startSaveName() {
            extPlan(this.saveName).then(res => {
                if (res.data) {
                    this.$message({
                        showClose: true,
                        message: '命名重复，请更改标绘方案名称',
                        type: 'warning',
                        offset: 500,
                    });
                } else {
                    this.treeData[0].label = this.saveName;
                    this.addNewPlan();
                }
            });
        },
        async addNewPlan() {
            let geoObj = Cesium.C_layerGroupHandle.saveProgramme(this.activeLayerParent);
            let obj = {
                name: this.saveName,
                content: JSON.stringify(this.treeData) + '|' + JSON.stringify(geoObj),
            };
            updatePlan(obj)
                .then(res => {
                    if (res.data) {
                        this.$message({
                            showClose: true,
                            message: '保存方案成功',
                            type: 'success',
                            offset: 500,
                        });
                        this.saveNameShow = false;
                        if (this.saveThen) {
                            this[this.saveThen]();
                        }
                    }
                })
                .catch(err => {
                    console.log(err);
                    this.$message({
                        showClose: true,
                        message: `err`,
                        type: 'warning',
                        offset: 500,
                    });
                });
        },
        closeRadio() {
            this.radioShow = false;
        },
        addLeafNode(data, primitive, flag = true) {
            data.type = primitive.getType();
            this.$refs.tree.append(data, this.activeLayer);
            this.$refs.tree.setChecked(data.id, flag);
            Cesium.C_layerGroupHandle.addGeometry(
                primitive,
                this.activeLayerParent,
                this.activeLayer
            );
        },
        getLayerId() {
            return {
                id: this.activeLayer,
                pId: this.activeLayerParent,
            };
        },
        cancel() {
            this.radioShow = false;
            this.savePanel = false;
            this.saveThen = null;
            this.saveNameShow = false;
        },
    },

    mounted() {
        document.addEventListener('click', this.closeMune, true);
        this.activeLayerParent = this.treeData[0].id;
        this.activeLayer = this.treeData[0].children[0].id;
        Cesium.C_layerGroupHandle.addLayerGroup(this.activeLayerParent, '默认方案');
        Cesium.C_layerGroupHandle.addLayer(this.activeLayerParent, this.activeLayer, '默认图层');
        Cesium.C_layerGroupHandle.setActiveLayer(this.activeLayerParent, this.activeLayer);
    },
    components: {
        contextmenu,
        markPage,
        Dialog,
    },
};
</script>

<style lang="scss">
@import './theme/css/draw.scss';
</style>
